import { ElDialog, ElInput, ElButton } from "element-plus";
import { createVNode, defineComponent, reactive, render } from "vue";

const DialogComponent = defineComponent({
  props: {
    options: {
      type: Object
    }
  },
  setup(props, ctx) {
    const state = reactive({
      options: props.options,
      isShow: false
    })

    // 对外 暴露方法
    ctx.expose({
      showDialog(options) {
        state.options = options
        state.isShow = true
      }
    })
    const onCancel = () => {
      state.isShow = false
    }
    const onConfirm = () => {
      state.isShow = false
      state.options.onConfirm(state.options.content)
    }
    return () => {
      return <ElDialog v-model={state.isShow} title={state.options.title}>
        {{
          default: () => <ElInput 
          type="textarea" 
          v-model={state.options.content} 
          rows={10}
          />, // 插槽是函数
          footer: () => state.options.footer && <div>
            <ElButton onClick={onCancel}>取消</ElButton>
            <ElButton type="primary" onClick={onConfirm}>确认</ElButton>
          </div>
        }}
      </ElDialog>
    }
  }
})

let vm
export function $dialog(options) {
  if (!vm) {
    // new SubComponent.$mount()
    let el = document.createElement('div')

    // 组件  渲染  虚拟节点
    vm = createVNode(DialogComponent, {options})
    render(vm, el)// 虚拟节点变为真节点  返回的是 undefined
    document.body.appendChild(el)
  }
  // 将组建渲染到 el 元素上

  let {showDialog} = vm.component.exposed
  showDialog(options)
}